# 导入所需的库
import cv2, Leap, math, ctypes
import numpy as np
import cPickle as pickle 

# 导入自定义支持函数
from supportFunctions import *

# 定义 Leap Motion 管理类
class leap(object):
    # 初始化函数
    def __init__(self):
        # 创建 Leap Motion 控制器对象
        self.controller = Leap.Controller()
        # 允许访问原始图像数据
        self.controller.set_policy(Leap.Controller.POLICY_IMAGES)
        # 用于存储图像的列表
        self.images = []

    # 拍摄快照函数
    def takeSnapshot(self):
        # 获取 Leap Motion 控制器的当前帧
        frame = self.controller.frame()
        # 仅获取左侧图像
        image = frame.images[0]

        # 将图像数据封装成 NumPy 数组
        i_address = int(image.data_pointer)
        ctype_array_def = ctypes.c_ubyte * image.height * image.width
        # 转换为 ctypes 数组
        as_ctype_array = ctype_array_def.from_address(i_address)
        # 转换为 NumPy 数组
        as_numpy_array = np.ctypeslib.as_array(as_ctype_array)
        rawImage = np.reshape(as_numpy_array, (image.height, image.width))

        # 获取图像的畸变矫正参数
        left_coordinates, left_coefficients = convert_distortion_maps(frame.images[0])

        # 使用 OpenCV 中的 remap 函数进行畸变矫正
        destination = cv2.remap(rawImage, left_coordinates, left_coefficients, interpolation=cv2.INTER_LINEAR)
        # 调整图像大小
        destination = cv2.resize(destination, (400, 400), 0, 0, cv2.INTER_LINEAR)

        # 将处理后的图像添加到列表中
        self.images.append(destination)

        print(str(len(self.images)) + ' images captured!')

    # 将图像保存为 pickle 文件函数
    def pickleImages(self, fileName):
        pickleFileName = fileName + ".pickle"
        # 打开 pickle 文件并将图像列表保存到文件中
        pickleFile = open(pickleFileName, 'wb')
        pickle.dump(self.images, pickleFile, pickle.HIGHEST_PROTOCOL)
        pickleFile.close()
